package com.example.java_gobang.api;

import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserAPI {

    @Resource  //@Resource注解和@Autowired注解一样  @Resource默认按照名字装配Bean，即会按照name属性的值来找到具有相同id的Bean Definition  并注入
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String userName, String password, HttpServletRequest req) {
        //根据username去数据库查询 账号密码一致则登录成功
        User user = userMapper.selectByName(userName);
        System.out.println("login username = "+ userName);
        if (user == null || !user.getPassword().equals(password)) {
            //登录失败
            log.info("登录失败");
            return new User();
        }
        HttpSession session = req.getSession(true);  //获取session,如果session不存在，就新建一个
        session.setAttribute("user", user);  //它的作用是在会话中存储一个用户对象，这样就可以在同一个会话的多个请求之间访问这个对象
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String userName, String password) {
        try {
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            userMapper.insert(user);
            return user;

        } catch (org.springframework.dao.DuplicateKeyException e) {
            User user = new User();  //失败返回一个空对象
            return user;
        }

    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        try {
            HttpSession session = req.getSession(false);
            User user = (User)session.getAttribute("user");  //本来是session强转成user对象
            //那这个user对象去数据库找,找到最新的数据
            User newUser = userMapper.selectByName(user.getUserName());
            return newUser;
        }catch (NullPointerException e){
            return new User();  //返回空对象
        }

    }
}
